import _ from "lodash";
import {
  IContainer, IPage, IWidget, IContainerCmpnt, IPageCmpnt, IWidgetCmpnt,
  isWidget, isContainer, isPage,
  isBars
} from "./index";
import { reactive } from "vue";

// 使用深拷贝复制组件  
const clone = (cmpt: IWidget | IContainer | IPage): IWidgetCmpnt | IContainerCmpnt | IPageCmpnt => {
  //添加id,clone方法
  let ncmpnt = _.cloneDeep(cmpt); // 使用lodash的深拷贝  
  setUniqueId(ncmpnt);
  ncmpnt.clone = () => clone(ncmpnt);
  ncmpnt.valueKey = ncmpnt.id // 组件的valueKey属性为组件id,方便查找组件数据
  ncmpnt.containers=reactive([])//构建一个包含自己的容器，用于组件内部切换。
  ncmpnt.containers.push(ncmpnt);
  if (isContainer(ncmpnt)) return ncmpnt as IContainerCmpnt;
  if (isPage(ncmpnt)) return ncmpnt as IPageCmpnt;
  if (isWidget(ncmpnt)) return ncmpnt as IWidgetCmpnt;
  if (isBars(ncmpnt)) return ncmpnt as IWidgetCmpnt;
  throw new Error(`组件类型错误${JSON.stringify(ncmpnt)}`);
};

// 为组件添加唯一ID属性  

const setUniqueId = (obj: IContainer | IPage | IWidget) => {
  obj["id"] = _.uniqueId("1000_");
  if (obj.children) {
    if (Array.isArray(obj.children) && obj.children.length > 0) {
      obj.children.forEach((child) => {
        setUniqueId(child);
      });
    }
  }
};



export { clone };